//
//  WeatherService.m
//  YouthOlympic2014
//
//  Created by Li Yuhang on 14-7-25.
//  Copyright (c) 2014年 mitian. All rights reserved.
//

#import "WeatherService.h"

@implementation WeatherService


- (void) getWeather: (NSString*) gameDate
         completion:(CompletionBlock)completion{
    
    //处理超时
    __block BOOL isResultCompletion = NO;
    
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, RESULT_TIME_MAX * NSEC_PER_SEC);
    dispatch_after(popTime,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        if (!isResultCompletion) {
            isResultCompletion = YES;
            NSString* errorMsg = @"timeout";
            NSError* error = [NSError errorWithDomain:errorMsg code:504 userInfo:nil];
            completion(nil,error);
        }
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSError* error = nil;
        NSString* weatherStr;
        NSDictionary* jsonData = [self.api GetWeather: gameDate withLan: [AppUtils getLan]];
        NSString* errorMsg = [[jsonData objectForKey:@"ApiErrorInfo"] objectForKey:@"msg"];
        
        if (errorMsg != nil) {
            error = [NSError errorWithDomain:errorMsg code:400 userInfo:nil];
        }else{
            weatherStr = jsonData[@"weather"];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!isResultCompletion) {
                isResultCompletion = YES;
                completion(weatherStr,error);
            }
        });
    });
}

@end
